<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*,java.io.*" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.json.JSONObject " %>
<%@page import="java.util.concurrent.locks.*" %>
<%@page import="org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper"%>
<%@ page import="cn.safetys.util.DateUtil" %>

<%
//允许上传的格式
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");
long maxSize = 204800000;
//Struts2 请求 包装过滤器
MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper)request;
//获得上传的文件名
String fileName = wrapper.getFileNames("imgFile")[0];
//获得未见过滤器
File file = wrapper.getFiles("imgFile")[0];
//----------重新构建上传文件名---------
final Lock lock = new ReentrantLock();
String newName = null;
lock.lock();
try{
//加锁为防止文件名重复
newName = System.currentTimeMillis()
  +fileName.substring(fileName.lastIndexOf("."),

  fileName.length());
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

//搜检扩大名 
 if(!Arrays.<String>asList(extMap.get("image").split(",")).contains(fileExt)){
    out.println(getError("上传文件扩展名是不容许的扩展名。\n只容许" + extMap.get("image") + "格式"));    return; } 
//搜检文件大小  
if (file.length() > maxSize) {
 out.println(getError("上传文件大小跨越限制2M。"));return;}




}finally{
lock.unlock();
}
//------锁结束---------

String dir=DateUtil.dateFormat(new Date(), DateUtil.SHORT_MODEL);
String savePath=request.getSession()
.getServletContext().getRealPath("/")
+"/images/upload/"+dir+"/" ;
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
    saveDirFile.mkdirs();
}
//获取文件输出流
FileOutputStream fos = new FileOutputStream(savePath+ newName);
//设置 KE 中的图片文件地址
String newFileName = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/images/upload/"+dir+"/"+ newName;
byte[] buffer = new byte[1024];
//获取内存中当前文件输入流
InputStream in = new FileInputStream(file);
try{
int num = 0;
while((num = in.read(buffer)) > 0){
fos.write(buffer,0,num);
}
}catch(Exception e){
e.printStackTrace(System.err);
}finally{
in.close();
fos.close();
}
//发送给 KE 


JSONObject obj = new JSONObject();
obj.put("error", 0);
obj.put("url", newFileName);
out.println(obj.toString());
%>
<%!
  private String getError(String message) {
	JSONObject obj = new JSONObject();
	try{
	obj.put("error", 1);
	obj.put("message",message);}catch(Exception e){
		
		
	}
	return obj.toString();
	}%>